/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if (root == null){
            return ans;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int count = 1;
        int max = root.val;
        while (!queue.isEmpty()) {
            if (count == queue.size()) {
                // 遍历完一层之后将这一层最大值放入结果列表，并初始化最大值和放入次数
                ans.add(max);
                max = Integer.MIN_VALUE;
                count = 0;
            }
            TreeNode poll = queue.poll();
            // 放入左右节点时，计算最大值
            if (poll.left != null) {
                max = Math.max(max, poll.left.val);
                queue.offer(poll.left);
                count++;
            }
            if (poll.right != null) {
                max = Math.max(max, poll.right.val);
                queue.offer(poll.right);
                count++;
            }
        }
        return ans;
    }
}
